package com.uvstu.common.utils;

import com.alibaba.fastjson2.JSONObject;
import com.uvstu.common.utils.sign.RSAUtils;

import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;

public class VerifyKeyUtils {

    /**
     * 激活码校验
     * @param key
     * @return
     */
    public static boolean verifyKey(String key){
        try{
            //解密
            key = RSAUtils.decryptByPublicKey(key);
            //密钥验证
            String[] arr = key.split("\\|");
            //获取mac
            String s = getMacAddress();
            //验证设备是否一致
            if(s.indexOf(arr[0]) != -1){
                //设备验证通过
                //验证码有效期
                String time = arr[1];
                SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date date = ft.parse(time);
                if(getNetworkTime() != null){
                    if(getNetworkTime().getTime() < date.getTime()){
                        return true;
                    }
                }else{
                    if(System.currentTimeMillis() < date.getTime()){
                        return true;
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 客户端生成验证秘钥
     */
    private static String getMacAddress(){
        String mac = null;
        try{
            if(MacUtils.getMAC() !=null){
                mac = MacUtils.getMAC();
            }else if(MacUtils.getMacAddress().size() != 0){
                mac = JSONObject.toJSONString(MacUtils.getMacAddress());
            }else if(MacUtils.getLinuxMACAddress().size() != 0){
                mac = JSONObject.toJSONString(MacUtils.getLinuxMACAddress());
            }else if(MacUtils.getMACAddressByWindows().size() != 0){
                mac = JSONObject.toJSONString(MacUtils.getLinuxMACAddress());
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return mac;
    }

    /**
     * 获取网络时间
     * @return
     */
    private static Date getNetworkTime() {
        try {
            URL url = new URL("http://www.baidu.com");
            URLConnection conn = url.openConnection();
            conn.connect();
            long dateL = conn.getDate();
            Date date = new Date(dateL);
            return date;
        } catch (Exception e) {}
        return null;
    }

    /**
     * 获取到期时间
     * @param key
     * @return
     */
    public static String getEndTime(String key) {
        String time = "--";
        try{
            //解密
            key = RSAUtils.decryptByPublicKey(key);
            //密钥验证
            String[] arr = key.split("\\|");
            //验证码有效期
            time = arr[1];
        }catch (Exception e){
            e.printStackTrace();
        }
        return time;
    }
}
